Completed
Push — master ( d362a9...56faa4 )
by Mark
14s queued 11s
created

Relation.getRelationalFields   A

Complexity

Conditions 3

Size

Total Lines 3
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 3
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
import Field from "./Field.js";
2
import ForeignKey from "./Field/ForeignKey";
3
import {ModelStaticInterface, TableInterface} from "../../JeloquentInterfaces";
4
5
/**
6
 *
7
 */
8
export default class Relation extends Field {
9
10
    foreignKey: string;
11
12
    model: ModelStaticInterface;
13
14
    constructor(model: ModelStaticInterface, foreignKey: string = null, name: string = null) {
15
        const className = name ?? model.snakeCaseClassName;
16
        super(className);
17
        this.model = model;
18
        this.foreignKey = foreignKey;
19
    }
20
21
    getRelationalFields(): Array<ForeignKey> {
22
        return [new ForeignKey(this.foreignKey).setRelation(this)];
23
    }
24
25
    tableSetup(table: TableInterface): void {
26
        table.registerIndex(this.foreignKey);
27
    }
28
29
    protected setFillPropertyOnParent(): void {
30
        Object.defineProperty(
31
            this.$parent,
32
            `_${this.$name}`,
33
            {
34
                set: (value) => {
35
                    if (!Array.isArray(value)) {
36
                        value = [value];
37
                    }
38
                    value.forEach((modelValue) => {
39
                        if (!(this.model.ids().includes(modelValue.id))) {
40
                            this.model.insert(modelValue);
41
                        }
42
                    });
43
                }
44
            });
45
    }
46
}